package com.tyros.common.kit.web.filter;

import com.tyros.common.kit.log.LogKit;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.UUID;

/**
 * 日志跟踪
 * <p>
 * TODO 待优化，transmittable-thread-local
 *
 * @author zhangshuaiyin
 * @date 2022/3/24 17:07
 */
@Slf4j
public class MdcFilter implements Filter {

    /**
     * 日志跟踪标识
     */
    private static final String TRACE_ID = "TRACE_ID";

    @Override
    public void init(FilterConfig filterConfig) {
        LogKit.debug(log, "初始化MDC过滤器");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        boolean init = initTrace(request);
        try {
            chain.doFilter(request, response);
        } finally {
            if (init) {
                LogKit.trace(log, "业务请求结束!");
                MDC.clear();
            }
        }
    }

    private boolean initTrace(ServletRequest servletRequest) {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        MDC.put(TRACE_ID, UUID.randomUUID().toString().trim().replaceAll("-", ""));
        MDC.put("URI", request.getRequestURI());
        return true;
    }

    @Override
    public void destroy() {
        LogKit.debug(log, "销毁MDC过滤器");
    }
}
